package com.lagou.service.impl;

import com.lagou.pojo.AuthCode;
import com.lagou.dao.CodeDao;
import com.lagou.feign.EmailServiceFeignClient;
import com.lagou.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author czq
 * @date 2020/9/15 17:04
 */
@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private EmailServiceFeignClient emailServiceFeignClient;

    @Autowired
    private CodeDao codeDao;

    /**
     * ⽣成验证码并发送到对应邮箱，成功true，失败false
     */
    @Override
    public boolean create(String email) {
        String code = getRandomNum();
        boolean result = emailServiceFeignClient.email(email, code);
        if (!result) {
            return false;
        }

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Date now = new Date();
        authCode.setCreatetime(now);
        authCode.setExpiretime(new Date(now.getTime() + 1000 * 60 * 10));
        codeDao.save(authCode);

        return true;
    }

    @Override
    public int validate(String email, String code) {

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);

        Example<AuthCode> example = Example.of(authCode);
        Sort expiretime = Sort.by(Sort.Direction.DESC, "expiretime");
        List<AuthCode> authCodeList = codeDao.findAll(example, expiretime);

        // 判断是否存在 code
        if (authCodeList.isEmpty()) {
            return 1;
        }

        // 判断是否超时
        AuthCode oldData = authCodeList.get(0);
        if (System.currentTimeMillis() > oldData.getExpiretime().getTime()) {
            return 2;
        }

        return 0;
    }

    /**
     * 为随机⽣成的6位数字
     */
    public static synchronized String getRandomNum(){
        return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    }
}
